/*
 * Powered By fanrenqij.com
 * Since 2017 - 2017
 */

package com.fanrenqiji.modules.business.course.web;


import com.fanrenqiji.common.config.GlobalSetting;
import com.fanrenqiji.common.persistence.Page;
import com.fanrenqiji.common.web.BaseController;
import com.fanrenqiji.modules.business.course.service.CourseService;
import com.fanrenqiji.modules.business.course.vo.CoursePageVO;
import com.fanrenqiji.modules.business.course.vo.CourseVO;
import com.fanrenqiji.modules.business.event.vo.EventVO;
import com.fanrenqiji.modules.business.eventcase.vo.EventCaseVO;
import com.fanrenqiji.modules.business.teacher.service.TeacherService;
import com.fanrenqiji.modules.business.teacher.vo.TeacherVO;
import com.fanrenqiji.modules.business.wechat.WeixinService;
import com.fanrenqiji.modules.business.wechatuser.service.WeChatUserService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping(value = "${adminPath}/business/course")
public class CourseController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(CourseController.class);
    @Autowired
    private CourseService courseService;
    @Autowired
    private TeacherService teacherService;

    @Autowired
    private WeChatUserService weChatUserService;
    @ModelAttribute("course")
    public CourseVO getCourse(@RequestParam(required = false) String id) {
        if (StringUtils.isNotEmpty(id)) {
            return courseService.get(id);
        } else {
            return new CourseVO();
        }
    }

    @RequiresPermissions("business:course:view")
    @RequestMapping(value = {"list", ""})
    public String all(CoursePageVO course, HttpServletRequest request,
                       HttpServletResponse response, Model model) {
        Page<CoursePageVO> coursePageVOPage = new Page<CoursePageVO>(request, response);
        coursePageVOPage.setPageSize(10);
        Page<CoursePageVO> page = courseService.findCourseByPage(coursePageVOPage,
                course);
        model.addAttribute("page", page);
        // 还需要将学科的集合查询出来
        model.addAttribute("course", course);
        //主讲老师的回显
        if (course.getTeacher() != null) {
            if (StringUtils.isNotBlank(course.getTeacher().getId())) {
                TeacherVO teacherVO = teacherService.get(course.getTeacher().getId());
                model.addAttribute("teachername", teacherVO.getName());
            }
        }

        return "modules/business/course/courseList";
    }

    /**
     * 用户添加更新表
     *
     * @param model
     * @return
     */
    @RequiresPermissions("business:course:edit")
    @RequestMapping(value = "form")
    public String form(Model model, CourseVO course) {
        //getSubject().isPermitted("business:course:my");

        if (StringUtils.isNotEmpty(course.getId())) {
            model.addAttribute("course", courseService.get(course.getId()));
        } else {
            model.addAttribute("course", course);
        }

        return "modules/business/course/courseForm";
    }

    /**
     * 添加或修改提交
     *
     * @param course
     * @param model
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("business:course:edit")
    @RequestMapping(value = "save")
    public String save(CourseVO course, String knowledgersid[], String gradeids[],
                       Model model,
                       RedirectAttributes redirectAttributes) {// TODO @Valid 添加后端校验
        if (!beanValidator(model, course)) {
            return form(model, course);
        }

        courseService.update(course, knowledgersid, gradeids);
        addMessage(redirectAttributes, "保存成功");
        return "redirect:" + GlobalSetting.getAdminPath()
                + "/business/course/?repage";
    }

    /**
     * 删除操作
     *
     * @return
     */
    @RequestMapping("delete")
    @RequiresPermissions("business:course:delete")
    public String delete(String id, RedirectAttributes redirectAttributes) {
        courseService.delete(id);
        addMessage(redirectAttributes, "删除成功");
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/course/";
    }

    /**
     * 放大镜
     *
     * @param response
     * @return
     */
    @RequestMapping("all")
    @ResponseBody
    public List<Map<String, Object>> all(HttpServletResponse response) {
        response.setContentType("application/json; charset=UTF-8");
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<CourseVO> courseVOList = courseService.getAll();
        for (int i = 0; i < courseVOList.size(); i++) {
            CourseVO vo = courseVOList.get(i);
            if (vo != null) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("name", vo.getSeq());
                map.put("id", vo.getId());
                mapList.add(map);
            }
        }
        return mapList;
    }


    /**
     * 用户添加更新表2 主要用来添加课程详情以及修改的
     *
     * @param model
     * @return
     */

    @RequiresPermissions("business:course:view")
    @RequestMapping(value = "form2")
    public String form2(Model model, CourseVO course) {
        if (StringUtils.isNotEmpty(course.getId())) {
            // 回显
            model.addAttribute("course", courseService.get(course.getId()));
        /*// 课程详情进行回显
		Set<CourseItemVO> courseItems = courseService.get(course.getId()).getCourseItems();
		String courseitemids ="";
		String courseitemsnames="";
		for (CourseItemVO courseItemVO:courseItems
				) {
			courseitemids+=","+courseItemVO.getId();
			courseitemsnames+=","+courseItemVO.getName();
		}
		model.addAttribute("courseitemids",courseitemids.substring(0));
		model.addAttribute("courseitemsnames",courseitemsnames.substring(0));*/
        } else {
            model.addAttribute("course", course);
        }
        return "modules/business/course/courseForm2";
    }

    /**
     * 查询已关联的集合
     *
     * @param response
     * @return
     */
    @RequestMapping("yiguanlian")
    @ResponseBody
    public List<Map<String, Object>> yiguanlian(HttpServletResponse response, String id) {
        response.setContentType("application/json; charset=UTF-8");
        List<Map<String, Object>> mapList = Lists.newArrayList();
        CourseVO courseVO = courseService.get(id);

        return mapList;
    }

    /**
     * 选择列表
     *
     * @return
     */
    @RequestMapping(value = "select")
    public String select(CoursePageVO courseVO, HttpServletRequest request,
                         HttpServletResponse response, Model model) {
        Page<CoursePageVO> page = courseService.findCourseByPage(new Page<CoursePageVO>(request, response, 10),
                courseVO);
        model.addAttribute("page", page);
        return "modules/business/course/courseSelect";
    }

    /**
     * 跳转添加事件的视图(作业)
     *
     * @param model
     * @param courseVO
     * @return
     */
    @RequestMapping(value = "addeventcase")
    @RequiresPermissions("business:course:addtask")
    public String addeventcase(Model model, CourseVO courseVO) {
        // 除了将课程查询出来 还要将课程下的set集合查询出来
        CourseVO courseVO1 = null;
        if (StringUtils.isNotBlank(courseVO.getId())) {
            courseVO1 = courseService.get(courseVO.getId());
            model.addAttribute("course", courseVO1);
        } else {
            model.addAttribute("course", courseVO1);
        }
        // 接下里就是添加事件的集合
        List<EventCaseVO> geteventcase = courseService.geteventcase(courseVO);
        model.addAttribute("eventcaselist", geteventcase);

        return "modules/business/course/addeventcase";
    }

    /**
     * 删除集合中指定事件 在业务成进行操作
     * @param courseid
     * @param eventid
     * @return
     */
	/*@RequestMapping(value = "removeevent")
	public 	String  removeevent(String courseid,String eventid){
		courseService.removeevent(courseid,eventid);
	return "redirect:"+GlobalSetting.getAdminPath()+"/business/course/addevent?id="+courseid;
	}*/

    /**
     * 课程里面添加指定的事件
     * @param courseid
     * @param eventid
     * @return
     */
	/*@RequestMapping(value = "saveventandcourse")
	public String saveventandcourse(String courseid,String eventid){
		courseService.savaeventandcourse(courseid,eventid);
		return "redirect:"+GlobalSetting.getAdminPath()+"/business/course/addevent?id="+courseid;
	}*/

    /**
     * 选择列表
     *
     * @return
     */
    @RequestMapping(value = "select3")
    public String select3(CoursePageVO courseVO, HttpServletRequest request,
                          HttpServletResponse response, Model model) {
        Page<CoursePageVO> page = courseService.findCourseByPage(new Page<CoursePageVO>(request, response, 10),
                courseVO);
        model.addAttribute("page", page);
        return "modules/business/courseitem/courseSelect3";
    }

    /***
     * 跳转教师备课的页面
     * @param courseVO
     * @return
     */
    @RequestMapping(value = "beike")
    @RequiresPermissions("business:course:beike")
    public String beike(CourseVO courseVO, Model model) {
        if (StringUtils.isNotBlank(courseVO.getId())) {
            CourseVO courseVO1 = courseService.get(courseVO.getId());
            model.addAttribute("course", courseVO1);
        } else {
            model.addAttribute("course", null);
        }
        // 暂时先将  集合传递过去  在页面展示的时候是src属性
        // 将已经关联的 图片 查询出来
        // 将第一张图片的id 放进去 用作点击


        return "modules/business/course/jiaoshibeike";
    }

    /**
     * 保存教师备课的方法 直接调用业务层方法即可
     *
     * @param courseVO
     * @param courseitemsids
     * @return
     */
    @RequestMapping(value = "savacourseitem")
    @RequiresPermissions("business:course:beike")
    public String savacourseitem(CourseVO courseVO, String courseitemsids, String courseitemsids2,Model model) {
        // 在这之前 要将上传上来的ids 进行校验
        //直接去业务层调用方法 然后重定向到展示页面
        if(StringUtils.isNotBlank(courseitemsids)){
            Integer jiaoyanyinpin = courseService.jiaoyanyinpin(courseitemsids);
            if(jiaoyanyinpin==1){
                // 说明是有错误的 那么就返回 并提示
                model.addAttribute("message","必须保证每个图片下 至少有一个音频文件");
                return "forward:" + GlobalSetting.getAdminPath() + "/business/course/beike";
            }
        }
        if (StringUtils.isNotBlank(courseitemsids2) || StringUtils.isNotBlank(courseitemsids) || courseVO != null) {
            courseService.savacourseitem(courseVO, courseitemsids, courseitemsids2);
            return "redirect:" + GlobalSetting.getAdminPath() + "/business/course/list";
        }
        return "redirect:" + GlobalSetting.getAdminPath() + "/business/course/list";
    }

    /**
     * 跳转添加事件实例页面的方法
     *
     * @param courseVO
     * @param model
     * @return
     */
    @RequestMapping(value = "addevent")
    @RequiresPermissions("business:course:addevent")
    public String addevent(CourseVO courseVO, Model model) {
        if (StringUtils.isNotBlank(courseVO.getId())
                ) {
            CourseVO courseVO1 = courseService.get(courseVO.getId());
            model.addAttribute("course", courseVO1);
        } else {
            model.addAttribute("course", null);
        }
        List<EventVO> eventByCourse = courseService.findEventByCourse(courseVO);

        ArrayList<EventVO> objects = Lists.newArrayList();
        for (EventVO eventCaseVO : eventByCourse) {
            objects.add(eventCaseVO);
        }
        model.addAttribute("eventlist", objects);
        return "modules/business/course/addevent";
    }

    @RequestMapping(value="begin")
    public void begin(CourseVO courseVO){
        CourseVO courseVO1 = courseService.get(courseVO.getId());

    }
}